<template>
    <div class="marketing_enough">
        <!-- 新增操作 -->
        <div class="marketing_enough_top">
            <el-row class="marketing_enough_header" :gutter="10">
                <el-col v-for="{ typeName, type, typeDesc } in groupTypeList" :key="type" :span="8">
                    <div class="marketing_enough_header_item">
                        <div>
                            <h3>
                                {{ typeName }}
                            </h3>
                            <p>{{ typeDesc }}</p>
                        </div>
                        <el-button type="primary" @click="routerHandler(type)" v-auth="'enough_list:create'"
                            >立即新增</el-button
                        >
                    </div>
                </el-col>
            </el-row>
        </div>
        <div class="marketing_enough_bottom">
            <!-- 查询 -->
            <div class="zw-form-layout">
                <el-form ref="formRef" :model="form" label-width="auto">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="活动名称" prop="activityName">
                                <el-input v-model="form.activityName" clearable placeholder="请输入活动名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="活动类型" prop="activityType">
                                <el-select v-model="form.activityType" placeholder="请选择状态">
                                    <el-option
                                        v-for="item in activityType"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="活动状态" prop="activityStatus">
                                <el-select v-model="form.activityStatus" placeholder="请选择状态">
                                    <el-option
                                        v-for="item in activityStatusList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="活动时间" prop="activityTime">
                                <el-date-picker
                                    v-model="form.activityTime"
                                    type="datetimerange"
                                    range-separator="至"
                                    :default-time="defaultTime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="16" class="zw-form-btns">
                            <el-button type="primary" @click="searchHandler" v-auth="'enough_list:view'"
                                >查询</el-button
                            >
                            <el-button plain @click="resetHandler">清空</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <!-- 列表 -->
            <el-table :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template
                        v-if="['activityTime', 'activityName', 'operations', 'realStatusName'].includes(prop)"
                        #default="{ row }">
                        <template v-if="prop === 'activityTime'">
                            {{ row.activityStartTime }}至<br />{{ row.activityEndTime }}
                        </template>
                        <template v-if="prop === 'activityName'">
                            <!-- <el-link type="primary" class="custom-el-link" @click="nameRouteHandler(row, 'group')">{{
                                row.activityName
                            }}</el-link> -->
                            <div class="custom-el-link">
                                <span @click="nameRouteHandler(row, 'group')">{{ row.activityName }}</span>
                            </div>
                        </template>
                        <template v-if="prop === 'realStatusName'">
                            <span :class="`custom-status-${row.realStatus}`">{{ row.realStatusName }}</span>
                        </template>
                        <template v-if="prop === 'operations'">
                            <el-button
                                v-for="{ label, fn, ref, auth } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                :ref="el => setItemRef(el, `${ref}${row.id}`)"
                                class="table-button"
                                v-auth="auth"
                                >{{ label }}</el-button
                            >
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-enough-popover-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :width="currentRow.ref === 'spreadButtonRef' ? 400 : 240"
            :visible="popoverVisible">
            <!-- todo:不同的内容 -->
            <div
                class="custom-enough-popover-class-main"
                v-click-outside="onClickOutside"
                v-if="['endButtonRef', 'removeButtonRef'].includes(currentRow.ref)">
                <template v-if="currentRow.ref == 'endButtonRef'">
                    <h3>
                        <el-icon class="custom-icon"><WarningFilled /></el-icon>你确定要结束吗？
                    </h3>
                    <!-- 未开始状态结束时确认提醒 -->
                    <p v-if="currentRow.realStatus == 1">结束后活动将无法启用</p>
                    <!-- 进行中状态结束时确认提醒 -->
                    <p v-else>结束后活动将立即结束，无法再次启用</p>
                </template>
                <!-- 删除 -->
                <h3 style="margin-bottom: 16px" v-if="currentRow.ref == 'removeButtonRef'">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>你确定要删除吗？
                </h3>
                <div style="text-align: right">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
            <SpreadBox
                v-if="popoverVisible && currentRow.ref === 'spreadButtonRef'"
                :path="path"
                :params="params"
                :downloadName="downloadName"
                :popoverFn="popoverVisibleHandler" />
        </el-popover>
    </div>
</template>

<script setup name="marketingEnough">
import { ref, unref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import { cloneDeep } from '../../../../commons/utils';
import store from '@/store/index';
import storage from '@/commons/storage';
import SpreadBox from '@/components/SpreadBox.vue';

const router = useRouter();
const activityStatusList = reactive(packSelectObjUtil(constants.GROUP_STATUS_OPTIONS));
const activityType = reactive(packSelectObjUtil(constants.ACTIVITY_TYPE));

// todo:优化代码结构
// 顶部新增和Tabs Dom
let groupTypeList = reactive([
    { typeName: '满x元减', typeDesc: '例：满200元减20元。助力商家提高客单价。', type: 7 },
    { typeName: '满x件折', typeDesc: '例：满3件打8折。助力商家提高连带率。', type: 8 }
]);
const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10, //默认每页15条
    activityStatus: 0, //活动状态  1-未开始 2-进行中 3-已结束
    activityName: '', //活动名
    activityType: 0, //0 所有 7 是满几元 8 满几件
    activityTime: [], //活动时间数组
    choiceSpike: 1 //1 代表 全部的  2-未开始和进行中的
});
let formClone = reactive(null);
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null, id: null, status: null });

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '活动名称', prop: 'activityName', showOverflowTooltip: true, minWidth: '200' },
        { label: '活动类型', prop: 'activityTypeText', width: '100' },
        { label: '活动详情', prop: 'activityInfo', width: '150', showOverflowTooltip: true },
        { label: '活动时间', prop: 'activityTime', width: '200' },
        { label: '活动状态', prop: 'realStatusName', width: '120' },
        { label: '参与客户数', prop: 'partakeCustomerNum', width: '100' },
        { label: '支付订单数', prop: 'payOrderNum', width: '100' },
        { label: '销售额（元）', prop: 'totalPayAmount', width: '110' },
        { label: '操作', prop: 'operations', width: '270', fixed: 'right' }
    ];
    if (form.activityType == 4) {
        // 老带新的表格列
        const columns = [...baseTableColumns];
        columns.splice(5, 0, { label: '参团新客户数', prop: 'groupNewCustNum' });
        return columns;
    }
    return baseTableColumns;
});

const nameRouteHandler = ({ id }, type) => {
    const useAuth = store.useAuthStore();
    const permissions = useAuth.permissions;
    const code = 'enough_list:view';
    if (!permissions.has(code)) {
        ElMessage({
            type: 'error',
            message: '当前用户没有查看权限'
        });
        return false;
    }
    const { href } = router.resolve({
        path: '/marketing/enough/detail',
        query: {
            id,
            type
        }
    });
    window.open(href, '_blank');
};
const routerHandler = type => {
    const paths = {
        7: '/marketing/enough/yuanAdd',
        8: '/marketing/enough/pieceAdd'
    };
    router.push({ path: paths[type] });
};
// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const res = await request('fullreduceList', form);
    const list = (res.data.list || []).map(item => {
        // todo: 根据不同状态显示不同按钮
        item.activityTime = `${item.activityStartTime}至${item.activityEndTime}`;
        item.realStatusName = item.activityStatusName.realStatusName;
        item.realStatus = item.activityStatusName.realStatus;
        item.activityTypeText = activityType.find(aItem => aItem.value == item.activityType)?.label;
        if (item.activityType == 7) {
            item.activityInfo = `满${item.orderAmount / 100}元减${item.reduce / 100}元`;
        } else {
            item.activityInfo = `满${item.orderAmount}件打${item.reduce / 10}折`;
        }
        item.totalPayAmount = item.totalPayAmount / 100;
        // todo:权限
        const btns = [
            { label: '编辑', fn: editHandler, ref: 'editButtonRef', auth: 'enough_list:edit' },
            { label: '推广', fn: spreadHandler, ref: 'spreadButtonRef', auth: 'enough_list:spread' },
            { label: '结束', fn: endHandler, ref: 'endButtonRef', auth: 'enough_list:end' },
            { label: '数据', fn: dataHandler, ref: 'dataButtonRef', auth: 'enough_list:view' },
            { label: '删除', fn: removeHandler, ref: 'removeButtonRef', auth: 'enough_list:delete' }
        ];
        if (item.realStatus == 1) {
            item.operations = [btns[0], btns[1], btns[2]];
        } else if (item.realStatus == 2) {
            item.operations = [btns[0], btns[1], btns[3], btns[2]];
        } else if (item.realStatus == 3) {
            item.operations = [btns[3], btns[4]];
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
    formClone = cloneDeep(form);
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryCouponListHandler();
};
/** 按钮组操作 */
const popoverHandler = ({ id, realStatus, activityName, codeUrl }, ref) => {
    buttonRef.value = itemRefs[`${ref}${id}`];
    currentRow.ref = ref;
    currentRow.id = id;
    currentRow.realStatus = realStatus;
    currentRow.activityName = activityName;
    currentRow.codeUrl = codeUrl;

    nextTick(() => {
        popoverVisible.value = true;
    });
};
// 编辑
const editHandler = row => {
    // todo:activityType
    const editType = {
        7: 'yuanEdit',
        8: 'pieceEdit'
    };
    router.push({
        path: `/marketing/enough/${editType[row.activityType]}`,
        query: {
            id: row.id
        }
    });
};
// 推广
let path = ref();
let params = ref();
let downloadName = ref();
const spreadHandler = async (row, ref) => {
    path.value = 'pages-cart/activeDetail/index';
    params.value = `activityId=${row.id}&shopId=${storage.get('ZW-SHOPID')}`;
    downloadName.value = row.activityName;
    popoverHandler(row, ref);
};
// 结束
const endHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 数据
const dataHandler = row => {
    nameRouteHandler(row, 'statistics');
};
// 删除
const removeHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    await request(`fullreduce${currentRow.ref === 'removeButtonRef' ? 'Del' : 'End'}`, { id: currentRow.id });
    popoverVisibleHandler();
    searchHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

//切换tab筛选
const tabHandler = () => {
    searchHandler();
};

const getAllData = () => {
    searchHandler();
};

onActivated(() => {
    Object.keys(formClone || {})?.forEach(key => {
        form[key] = formClone[key];
    });
    getAllData();
    setLayout();
});
onDeactivated(() => {
    resetLayout();
});
</script>
<style lang="scss">
.custom-enough-popover-class {
    padding: 0px !important;
    &-main {
        padding: 16px !important;
    }
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        margin-bottom: 10px;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 0 0 16px;
    }

    p + div {
        text-align: right;
    }
}
</style>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
